package com.dave.weixin.common.netty.chat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * @Author Dave
 * @Date 2018/7/16
 * @Description
 */
public class SimpleChatClient {
    private int port;
    private String address;

    public SimpleChatClient(String address, int port) {
        this.port = port;
        this.address = address;

    }

    public void run() {
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            Bootstrap b = new Bootstrap()
                    .group(worker)
                    .channel(NioSocketChannel.class)
                    .handler(new SimpleChatClientInitializer());

            //建立连接
            Channel channel = b.connect(address, port).sync().channel();

            //转换流
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                channel.writeAndFlush(in.readLine() + "\r\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }


    public static void main(String[] args) throws Exception {
        new SimpleChatClient("localhost", 9999).run();
    }
}
